//
//  BoardsViewController.m
//  ViewPoint
//
//  Created by Demiao Lin on 10/20/08.
//  Copyright 2008 Tsinghua. All rights reserved.
//

#import "BoardsViewController.h"

#import "DataStore.h"
#import "NewSMTH.h"

#import "ThreadsViewController.h"
#import "PostsViewController.h"

#define BoardsCount 7
#define INDICATOR_VIEW	999


@implementation BoardsViewController

@synthesize boards;
@synthesize threadsViewController;
@synthesize postsViewController;

- (id)init{
	if( (self=[super init]) != nil ){
		[self setThreadsViewController: [[[ThreadsViewController alloc] init] autorelease]];
		[self setPostsViewController: [[[PostsViewController alloc] init] autorelease]];
	}
	return self;
}


- (id) initWithTitle: (NSString *) title {
	if( (self=[self init]) != nil ){
		[self setTitle: title];
	}
	return self;
}

- (void)loadView
{
	CGRect rect = [[UIScreen mainScreen] applicationFrame];
    
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Edit" 
                                                                               style:UIBarButtonItemStylePlain 
                                                                              target:self 
                                                                              action:@selector(enterBoardsEditMode)] autorelease];
	
	UITableView *oneTableView = [[UITableView alloc] initWithFrame:rect
                                                             style:UITableViewStylePlain];
    oneTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    oneTableView.delegate = self;
    oneTableView.dataSource = self;
    self.tableView = oneTableView;
	//self.view = self.tableView;
    [oneTableView release];
	
    
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 32.0f, 32.0f)];
	//[activityIndicator setCenter:CGPointMake(rect.size.width/2, rect.size.height/2)];
    [activityIndicator setActivityIndicatorViewStyle:UIActivityIndicatorViewStyleGray];
	activityIndicator.tag = INDICATOR_VIEW;
    [self.view addSubview:activityIndicator];
    [activityIndicator release];
    
    //[self setViewsRotation];
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
    [self setViewsRotation];
}

- (void)viewDidAppear:(BOOL)animated {
	[super viewDidAppear:animated];
	[self loadTableView];
}

- (void)viewWillDisappear:(BOOL)animated {
}
- (void)viewDidDisappear:(BOOL)animated {
}

-(void) loadTableViewData:(id)object{
	NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    
	if(self.boards==nil || [self.boards count]<=0){
        DataStore *dataStore = [[[DataStore alloc] init] autorelease];
        NSMutableArray *array = [dataStore getFavouriteBoards];
        
        if(array==nil || [array count]<=0){
			array = [[[[NewSMTH alloc] init] autorelease] getBoards];
		}
		if(array!=nil && [array count]>0){
			self.boards = array;
			[self.tableView reloadData];
		}
	}
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
	[activityIndicator stopAnimating];
	[pool release];
}

-(void) loadTableView{
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
    [activityIndicator startAnimating];
	//[self loadTableViewData];
    [self performSelectorInBackground:@selector(loadTableViewData:) withObject:nil];
	//[NSThread detachNewThreadSelector:@selector(loadTableViewData:) toTarget:self withObject:nil];
    
}

- (void)enterBoardsEditMode{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Done" 
                                                                               style:UIBarButtonItemStylePlain 
                                                                              target:self 
                                                                              action:@selector(leaveBoardsEditMode)] autorelease];
	[self.tableView setEditing:YES animated:YES];
	[self.tableView beginUpdates];
    [pool release];
}

- (void)leaveBoardsEditMode{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Edit" 
                                                                               style:UIBarButtonItemStylePlain 
                                                                              target:self 
                                                                              action:@selector(enterBoardsEditMode)] autorelease];
	DataStore *dataStore = [[[DataStore alloc] init] autorelease];
    [dataStore saveFavouriteBoards:self.boards];
    
    [self.tableView endUpdates];
	[self.tableView setEditing:NO animated:YES];
	
	[self.tableView reloadData];
    [pool release];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.boards count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    Board *board = [self.boards objectAtIndex:[indexPath row]];
    //NSString *CellIdentifier = [NSString stringWithFormat:@"Boards_%d", [board bid]];
    NSString *CellIdentifier = @"BoardsCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
		cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	}
    cell.text = [NSString stringWithFormat:@"%02d-%@ [%@]", [indexPath row]+1, [board bname], [board desc] ];
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	Board *board = [self.boards objectAtIndex:[indexPath row]];
	//NSLog(@"board name:%@", [board bname]);
	[self.postsViewController setTitle:[board bname] board:board ];
	//NSLog(@"pushViewController title:%@", [self.postsViewController title]);
	[[self navigationController] pushViewController:self.postsViewController animated:YES];
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
	Board *board = [self.boards objectAtIndex:[indexPath row]];
	[self.threadsViewController setTitle:[board bname] board:board ];
	[[self navigationController] pushViewController:self.threadsViewController animated:YES];
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
                                            forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
		[self.boards removeObjectAtIndex: [indexPath row]];
		[tableView reloadData];
        [tableView flashScrollIndicators];
    }
    if (editingStyle == UITableViewCellEditingStyleInsert) {
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
	return UITableViewCellEditingStyleDelete;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
	//[self.boards exchangeObjectAtIndex:[fromIndexPath row] withObjectAtIndex:[toIndexPath row]];
    Board *board = [[self.boards objectAtIndex:[fromIndexPath row]] retain];
    [self.boards removeObjectAtIndex:[fromIndexPath row]];
    [self.boards insertObject:board atIndex:[toIndexPath row]];
    [board release];
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    //return (interfaceOrientation == UIInterfaceOrientationPortrait);
	return YES;
}

- (void) willAnimateSecondHalfOfRotationFromInterfaceOrientation:(UIInterfaceOrientation) fromOrientation duration:(NSTimeInterval) duration{
    [self setViewsRotation];
}

- (void) setViewsRotation {
    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self.view viewWithTag:INDICATOR_VIEW];
    UIInterfaceOrientation orientation = self.interfaceOrientation;
    if(orientation==UIInterfaceOrientationLandscapeLeft || orientation==UIInterfaceOrientationLandscapeRight){
        [activityIndicator setCenter:CGPointMake(240, 150)];
	}else{
        [activityIndicator setCenter:CGPointMake(160, 200)];
	}
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc {
	[boards release];
	[postsViewController release];
	[threadsViewController release];
    [super dealloc];
}

@end

